﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq.Expressions;

namespace Member.DAL
{
    public partial class BaseDAL<T>where T:class,new()
    {
        private DbContext dbcontext = DbContextFactory.Create();

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="t"></param>
        public void Add(T t)
        {
            dbcontext.Set<T>().Add(t);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="t"></param>
        public void Delete(T t)
        {
            dbcontext.Set<T>().Remove(t);
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="t"></param>
        public void Update(T t)
        {
            dbcontext.Set<T>().AddOrUpdate(t);
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="WhereLambda">条件表达式</param>
        /// <returns></returns>
        public IQueryable<T> GetModels(Expression<Func<T, bool>> WhereLambda)
        {
            return dbcontext.Set<T>().Where(WhereLambda);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="Type"></typeparam>
        /// <param name="pageSize">页大小</param>
        /// <param name="pageIndex">页数</param>
        /// <param name="isAsc">是否排序</param>
        /// <param name="OrderByLambda">排序字段</param>
        /// <param name="WhereLambda">条件表达式</param>
        /// <returns></returns>
        public IQueryable<T> GetModelsByPage<Type>(int pageSize,int pageIndex,bool isAsc,
            Expression<Func<T, Type>> OrderByLambda, Expression<Func<T, bool>> WhereLambda)
        {
            //是否排序
            if (isAsc)
            {
                return dbcontext.Set<T>().Where(WhereLambda).OrderBy(OrderByLambda).Skip((pageIndex-1)*pageSize).Take(pageSize);

            }
            else
            {
                return dbcontext.Set<T>().Where(WhereLambda).OrderByDescending(OrderByLambda).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
        }

        /// <summary>
        /// 保存在数据库
        /// </summary>
        /// <returns></returns>
        public bool SaveChange()
        {
            return dbcontext.SaveChanges()>0;
        }

    }
}
